package com.example.minilark.presentation.contacts

import android.graphics.drawable.ColorDrawable
import android.util.Log
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material.icons.filled.Search
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import coil.compose.AsyncImage
import coil.request.ImageRequest
import com.example.minilark.data.model.Contact
import com.example.minilark.data.oss.OSSManager

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ContactsScreen(
    username: String,
    viewModel: ContactsViewModel = hiltViewModel()
) {
    val state by viewModel.state.collectAsState()
    var searchQuery by remember { mutableStateOf("") }

    LaunchedEffect(Unit) {
        viewModel.loadContacts()
    }

    val filteredContacts = state.contacts.filter { contact ->
        contact.username.contains(searchQuery, ignoreCase = true)
    }

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text("联系人") },
                actions = {
                    IconButton(onClick = { viewModel.refreshContacts() }) {
                        Icon(Icons.Default.Refresh, contentDescription = "Refresh")
                    }
                }
            )
        }
    ) { paddingValues ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(paddingValues)
        ) {
            // 搜索框
            OutlinedTextField(
                value = searchQuery,
                onValueChange = { searchQuery = it },
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(16.dp),
                placeholder = { Text("搜索联系人") },
                leadingIcon = {
                    Icon(Icons.Default.Search, contentDescription = "Search")
                },
                singleLine = true
            )

            Box(modifier = Modifier.weight(1f)) {
                if (state.isLoading) {
                    CircularProgressIndicator(
                        modifier = Modifier.align(Alignment.Center)
                    )
                } else if (state.error != null) {
                    Text(
                        text = state.error ?: "未知错误",
                        color = MaterialTheme.colorScheme.error,
                        modifier = Modifier
                            .align(Alignment.Center)
                            .padding(16.dp)
                    )
                } else {
                    LazyColumn(
                        modifier = Modifier.fillMaxSize(),
                        contentPadding = PaddingValues(horizontal = 16.dp),
                        verticalArrangement = Arrangement.spacedBy(8.dp)
                    ) {
                        items(
                            items = filteredContacts,
                            key = { it.username }
                        ) { contact ->
                            ContactItem(contact = contact, viewModel = viewModel)
                        }
                    }
                }
            }
        }
    }
}

@Composable
private fun ContactItem(
    contact: Contact,
    modifier: Modifier = Modifier,
    viewModel: ContactsViewModel = hiltViewModel()
) {
    val surfaceVariant = MaterialTheme.colorScheme.surfaceVariant
    val errorColor = MaterialTheme.colorScheme.error
    
    Card(
        modifier = modifier.fillMaxWidth(),
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp),
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.spacedBy(16.dp)
        ) {
            // 头像
            Box(
                modifier = Modifier
                    .size(48.dp)
                    .clip(CircleShape)
                    .background(surfaceVariant),
                contentAlignment = Alignment.Center
            ) {
                val context = LocalContext.current
                val placeholderDrawable = remember {
                    ColorDrawable(surfaceVariant.toArgb())
                }
                val errorDrawable = remember {
                    ColorDrawable(errorColor.toArgb())
                }

                // 从URL中提取对象键
                val objectKey = remember(contact.profilePicture) {
                    contact.profilePicture.substringAfter("aliyuncs.com/")
                        .substringBefore("?")
                }

                // 使用 ViewModel 获取签名URL
                var imageUrl by remember { mutableStateOf(contact.profilePicture) }
                LaunchedEffect(objectKey) {
                    try {
                        imageUrl = viewModel.getSignedImageUrl(objectKey)
                    } catch (e: Exception) {
                        Log.e("ContactsScreen", "Failed to get signed URL", e)
                    }
                }
                
                AsyncImage(
                    model = ImageRequest.Builder(context)
                        .data(imageUrl)
                        .crossfade(true)
                        .size(144)
                        .placeholder(placeholderDrawable)
                        .error(errorDrawable)
                        .memoryCacheKey(objectKey)
                        .diskCacheKey(objectKey)
                        .build(),
                    contentDescription = "Avatar for ${contact.username}",
                    modifier = Modifier.fillMaxSize(),
                    contentScale = ContentScale.Crop,
                    onLoading = {
                        Log.d("ContactsScreen", "Loading avatar for ${contact.username}")
                    },
                    onSuccess = { state ->
                        Log.d("ContactsScreen", "Successfully loaded avatar for ${contact.username}")
                    },
                    onError = { state ->
                        Log.e("ContactsScreen", "Failed to load avatar for ${contact.username}: ${state.result.throwable}")
                        Log.e("ContactsScreen", "URL attempted: $imageUrl")
                    }
                )
            }

            // 用户名
            Text(
                text = contact.username,
                style = MaterialTheme.typography.titleMedium,
                modifier = Modifier.weight(1f)
            )
        }
    }
} 